package Algorithm.LinkedListProblem;

/**
 * @Author cj
 * @Date 2021/11/21 10:40
 */
public class reversePart {

    static class Node {
        public int value;
        public Node next;

        public Node(int val) {
            this.value = val;
        }
    }

    public static Node reversePart1(Node head, int from, int to) {
        int len = 0;
        Node node1 = head;
        Node fNode = null;
        Node tNode = null;
        while (node1 != null) {
            len++;
            fNode = len == from - 1 ? node1 : fNode;
            tNode = len == to + 1 ? node1 : tNode;
            node1 = node1.next;
        }
        if (!(1 <= from && from <= to && to <= len)) {
            return head;
        }
        // 旋转
        node1 = fNode == null ? head : fNode.next;
        Node startNode = node1;
        Node pre = null;
        Node after = null;
        int index = from;
        while (index <= to) {
            after = node1.next;
            node1.next = pre;
            pre = node1;
            node1 = after;
            index++;
        }
        // 拼接头尾
        if (fNode != null) {
            fNode.next = pre;
            startNode.next = tNode;
            return head;
        } else { // 从头节点开始转
            startNode.next = tNode;
            return pre;
        }
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);
        Node a = reversePart1(head, 5, 5);
        while (a != null) {
            System.out.println(a.value);
            a = a.next;
        }
    }
}
